<?php

namespace app\admin\logic\crm;

use app\admin\logic\BaseLogic;
use app\common\model\CrmCustomerMetas;
use app\common\model\CrmCustomers;
use app\common\model\CrmFollowUps;
use app\common\model\SystemUser;
use app\common\service\OpenSpoutWriter;
use app\common\service\SystemDictService;
use think\facade\Db;
use Webman\Event\Event;

/**
 * 客户跟进记录逻辑层
 * 用于处理客户跟进记录的业务逻辑
 */
class CrmFollowUpsLogic extends BaseLogic
{
    protected $scope = true;
    /**
     * 构造方法
     */
    public function __construct()
    {
        $this->model = new CrmFollowUps();
    }
    
    public function getFollowUpList(array $params): array
    {
        $where = [];
        // 按客户筛选
        if (!empty($params['customer_id'])) {
            $where['customer_id'] = $params['customer_id'];
        }
        
        // 按跟进人筛选
        if (!empty($params['user_id'])) {
            $where['user_id'] = $params['user_id'];
        }
        // 按跟进方式筛选
        if (!empty($params['type'])) {
            $where['type'] = $params['type'];
        }
        if (!empty($params['result'])) {
            $where['result'] = $params['result'];
        }
        
        if (!empty($userId)) {
            $where['user_id'] = $userId;
        }
        
        if (!empty($params['name'])) {
            $params['name'] = trim(strip_tags($params['name']));
        }
        
        $query = $this->search($where)->alias('f')
            ->when(!empty($params['name']), function ($query) use ($params) {
                $subQuery = CrmCustomers::alias('c')
                    ->leftJoin(CrmCustomerMetas::getTable().' m', 'c.id = m.customer_id')
                    ->where('m.delete_time', null)
                    ->whereIn('m.meta_key', ['contact_name', 'contact_person'])
                    ->whereLike('m.meta_value', "%{$params['name']}%")
                    ->where('c.delete_time', null)
                    ->whereRaw('f.customer_id = c.id')->buildSql(true);
                $query->whereExists($subQuery);
            })
            ->when(!empty($params['user']), function ($query) use ($params) {
                $subQuery = SystemUser::alias('u')->where('u.nickname', 'like', "%{$params['user']}%")->where('f.user_id', Db::raw('u.id'))->buildSql(true);
                
                $query->whereExists($subQuery);
            })
            ->when(!empty($params['area_id']), function ($query) use ($params) {
                $query->whereExists(CrmCustomers::alias('c')->where(function ($query) use ($params) {
                    $query->where('c.province_id', $params['area_id'])->whereOr('c.city_id', $params['area_id'])->whereOr('c.area_id', $params['area_id']);
                })->whereRaw('f.customer_id = c.id')->buildSql(true));
            })
            ->with(['customer', 'user', 'partner']);
        // 按时间范围筛选
        if (!empty($params['create_time'])) {
            $query->whereTime('create_time', 'between', parseDateRange($params['create_time'], ',', true, 'Y-m-d H:i:s'));
        }
        if (!empty($params['followup_time'])) {
            $query->whereTime('followup_time', 'between', parseDateRange($params['followup_time'], ',', true, 'Y-m-d H:i:s'));
        }
        if ($this->scope) {
            $query = $this->userDataScope($query);
        }
        // 分页
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        
        $list = $query->order('create_time', 'desc')->paginate(['list_rows' => $limit, 'page' => $page]);
        
        return $list->toArray();
    }

    
    /**
     * 保存跟进记录
     * @param array $data
     * @return mixed
     */
    public function save(array $data)
    {
        // 处理图片数组
        if (isset($data['images']) && is_array($data['images'])) {
            $data['images'] = array_values(array_filter($data['images']));
        }

        if (empty($data['followup_time'])) {
            $data['followup_time'] = date('Y-m-d H:i:s');
        }
        
        try {
            $this->model->transaction(function () use ($data) {
                //$this->model->save($data);
                
                $customerInfo = CrmCustomers::findOrEmpty($data['customer_id']);
                $baseData = $customerInfo->toArray();
                if ($customerInfo->isEmpty()) {
                    throw new \Exception('客户不存在');
                }
                if ($customerInfo->stage == 1) {
                    $customerInfo->stage = 2;
                }
                $customerInfo->follow_up_count = Db::raw('follow_up_count+1');
                $customerInfo->follow_up_time = empty($data['followup_time']) ? date('Y-m-d H:i:s') : $data['followup_time'];
                $customerInfo->save();

                
                Event::emit('customer.changed', [
                    'customerId' => $customerInfo->id,
                    'eventType' => '新增跟进',
                    'originalCustomerData' => $baseData,
                    'newCustomerData' => $customerInfo->toArray(),
                ]);
            });
        } catch (\Exception $e) {
            return false;
        }
        

        return $this->model->create($data);
    }

    /**
     * 更新跟进记录
     * @param int $id
     * @param array $data
     * @return mixed
     */
    public function update(int $id, array $data)
    {
        // 处理图片数组
        if (isset($data['images']) && is_array($data['images'])) {
            $data['images'] = array_values(array_filter($data['images']));
        }

        if (empty($data['followup_time'])) {
            unset($data['followup_time']);
        }

        return $this->model->where('id', $id)->update($data) !== false;
    }
    
    public function export(array $params)
    {
        $where = [];
        // 按客户筛选
        if (!empty($params['customer_id'])) {
            $where['customer_id'] = $params['customer_id'];
        }
        
        // 按跟进人筛选
        if (!empty($params['user_id'])) {
            $where['user_id'] = $params['user_id'];
        }
        // 按跟进方式筛选
        if (!empty($params['type'])) {
            $where['type'] = $params['type'];
        }
        if (!empty($params['result'])) {
            $where['result'] = $params['result'];
        }
        
        if (!empty($userId)) {
            $where['user_id'] = $userId;
        }
        
        if (!empty($params['name'])) {
            $params['name'] = trim(strip_tags($params['name']));
        }
        
        $query = $this->search($where)->alias('f')
            ->when(!empty($params['name']), function ($query) use ($params) {
                $subQuery = CrmCustomers::alias('c')
                    ->leftJoin(CrmCustomerMetas::getTable().' m', 'c.id = m.customer_id')
                    ->where('m.delete_time', null)
                    ->whereIn('m.meta_key', ['contact_name', 'contact_person'])
                    ->whereLike('m.meta_value', "%{$params['name']}%")
                    ->where('c.delete_time', null)
                    ->whereRaw('f.customer_id = c.id')->buildSql(true);
                $query->whereExists($subQuery);
            })
            ->when(!empty($params['user']), function ($query) use ($params) {
                $subQuery = SystemUser::alias('u')->where('u.nickname', 'like', "%{$params['user']}%")->where('f.user_id', Db::raw('u.id'))->buildSql(true);
                
                $query->whereExists($subQuery);
            })
            ->when(!empty($params['area_id']), function ($query) use ($params) {
                $query->whereExists(CrmCustomers::alias('c')->where(function ($query) use ($params) {
                    $query->where('c.province_id', $params['area_id'])->whereOr('c.city_id', $params['area_id'])->whereOr('c.area_id', $params['area_id']);
                })->whereRaw('f.customer_id = c.id')->buildSql(true));
            })
            ->with(['customer', 'user', 'partner']);
        // 按时间范围筛选
        if (!empty($params['create_time'])) {
            $query->whereTime('create_time', 'between', parseDateRange($params['create_time'], ',', true, 'Y-m-d H:i:s'));
        }
        
        $list = $query->order('create_time', 'desc')->cursor();
        
        $dictType = SystemDictService::getDictData('follow_up_type');
        $dictResult = SystemDictService::getDictData('follow_up_result');
        $dictType = array_column($dictType, 'label', 'value');
        $dictResult = array_column($dictResult, 'label', 'value');
        
        $export = [];
        foreach ($list as $item) {
            if (!empty($item['customer']['metas'])) {
                $metas = $item['customer']['metas'];
                $_tmp = [];
                foreach ($metas as $meta) {
                    $_tmp[$meta['meta_key']] = $meta['meta_value'];
                }
                $item['customer']['metas'] = $_tmp;
            } else {
                $item['customer']['metas'] = [];
            }
            
            $export[] = [
                '客户名称' => $item['customer']['metas']['contact_name'] ?? '',
                '客户代表' => $item['customer']['metas']['contact_person'] ?? '',
                '联系方式' => $item['customer']['metas']['phone'] ?? '',
                '跟进人' => $item['user']['nickname'] ?? '',
                '陪同人' => $item['partner']['nickname'] ?? '',
                '跟进方式' => $dictType[$item['type']] ?? $item['type'],
                '跟进结果' => $dictResult[$item['result']] ?? $item['result'],
                '跟进时间' => $item['create_time'],
                '跟进地址' => $item['address'],
                '跟进内容' => $item['content'],
            ];
        }
        $fileName = '客户跟进记录_'.date('YmdHis').'.xlsx';
        $header = ['客户名称', '客户代表', '联系方式', '跟进人', '陪同人', '跟进方式', '跟进结果', '跟进时间', '跟进地址', '跟进内容',];
        $width = [];
        foreach ($header as $key => $item) {
            $width[$key] = 18;
        }
        $writer = new OpenSpoutWriter($fileName);
        $writer->setHeader($header);
        $writer->setWidth(array_values($width));
        $writer->setData($export);
        $filePath = $writer->returnFile();
        return response()->download($filePath, urlencode($fileName));
    }
    
    /**
     * 删除跟进记录
     * @param $ids
     * @return mixed
     */
    public function destroy($ids)
    {
        foreach ($ids as $id) {
            $item = $this->model->find($id);
            if (!$item) {
                continue;
            }
            $item->delete();
            $userInfo = SystemUser::find($item->user_id);
            Event::emit('customer.changed', [
                'customerId' => $item->customer_id,
                'eventType' => '删除跟进',
                'description' => '删除 ' . ($userInfo->nickname ?? '') . ' 在 '. ($item->followup_tim ?? $item->create_time) .' 的跟进信息',
            ]);
        }
    }
    
}